dfs and similar dp greedy trees *1800

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
using ll = long long;



int main () {
  ll T_; cin >> T_;

  auto DO_ = [&] () -> void {
    ll n, k; cin >> n >> k;
    ll x, y; cin >> x >> y;

    vector <ll> spc (k);
    map <ll, ll> imp; imp[y] = 1;
    
    for (auto &val : spc) {
      cin >> val; imp[val] = 1;
    }

    vector <vector <ll>> adj (n + 1);
    for (ll i = 0; i < n - 1; i ++) {
      ll u, v; cin >> u >> v;
      adj[u].push_back(v);
      adj[v].push_back(u);
    }

    vector <ll> dp (n + 1);
    vector <ll> dpth (n + 1);

    auto dfs1 = [&] (ll node, ll par, auto& dfs1) -> void {
      for (auto child : adj[node]) {
        if (child == par) continue;
        dpth[child] = dpth[node] + 1;
        dfs1 (child, node, dfs1);
        if (dp[child]) dp[node] = 1;
      }
      if (imp[node]) dp[node] = 1;
    };

    dfs1 (x, -1, dfs1);

    int ans = 0;
    auto dfs2 = [&] (ll node, ll par, auto& dfs2) -> void {
      for (auto child : adj[node]) {
        if (child == par) continue;
        dfs2 (child, node, dfs2);
        if (dp[child]) ans += 2;
      }
    };

    dfs2 (x, -1, dfs2);

    cout << ans - dpth[y] << endl;
  };

  for (ll i = 1; i <= T_; i++) {
    DO_();
  }
  // DO_();
}


Comments

Submit
0 Comments
More Questions

489B - BerSU Ball
977C - Less or Equal
1505C - Fibonacci Words
1660A - Vasya and Coins
1660E - Matrix and Shifts
1293B - JOE is on TV
1584A - Mathematical Addition
1660B - Vlad and Candies
1472C - Long Jumps
1293D - Aroma's Search
918A - Eleven
1237A - Balanced Rating Changes
1616A - Integer Diversity
1627B - Not Sitting
1663C - Pōja Verdon
1497A - Meximization
1633B - Minority
688B - Lovely Palindromes
66B - Petya and Countryside
1557B - Moamen and k-subarrays
540A - Combination Lock
1553C - Penalty
1474E - What Is It
1335B - Construct the String
1004B - Sonya and Exhibition
1397A - Juggling Letters
985C - Liebig's Barrels
115A - Party
746B - Decoding
1424G - Years